<?php

namespace app\api\library;

use Exception;
use think\exception\Handle;
use think\Request;

/**
 * 自定义API模块的错误显示
 */
class ExceptionHandle extends Handle
{

    public function render(Exception $e)
    {
        // 在生产环境下返回code信息
        if (!\think\Config::get('app_debug')) {
            $statuscode = $code = 500;
            $msg = 'An error occurred';
            // 验证异常
            if ($e instanceof \think\exception\ValidateException) {
                $code = 0;
                $statuscode = 200;
                $msg = $e->getError();
            }
            // Http异常
            if ($e instanceof \think\exception\HttpException) {
                $statuscode = $code = $e->getStatusCode();
            }
	
            
            $result =['code' => $code, 'msg' => $e->getMessage(), 'time' => time(), 'data' => null];
            $this->addErrorLog($result);
            $result['msg'] = $msg;
            return json($result, $statuscode);
        }

        //其它此交由系统处理
        return parent::render($e);
    }

    public function addErrorLog($data) {
    	$dir = RUNTIME_PATH.'/errorLog/';
    	if(!is_dir($dir)) {
    		mkdir($dir, 0777, true);
	    }
    	
	    $req = Request::instance();
    	
    	$data = [
    		'time' => date('Y-m-d H:i:s'),
    		'url' => $req->url(),
		    'get' => $req->get(),
		    'post' => $req->post(),
		    'header' => $req->header(),
		    'return' => $data
	    ];
	    $log = var_export($data,true)."\r\n";
	
	    file_put_contents($dir.date('Y-m-d').'.txt',$log."\r\n",FILE_APPEND);
    }
}
